﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using EPiServer.Framework.Serialization;
using EPiServer.PlugIn;
using OpenWaves.EPiServer.CustomProperties;

namespace OpenWaves.EPiServer.TagsProperty
{
    [PropertyDefinitionTypePlugIn(DisplayName = "Tags List")]
    public class PropertyTags : LongStringProperty<IEnumerable<string>>
    {
        public const string UIHint = "PropertyTags";

        private readonly IObjectSerializer _serializer;

        private static IObjectSerializer GetSerializer()
        {
            var objectSerializerFactory = global::EPiServer.ServiceLocation.ServiceLocator.Current.GetInstance<IObjectSerializerFactory>();
            var objectSerializer = objectSerializerFactory.GetSerializer(KnownContentTypes.Json);
            return objectSerializer;
        }
        
        public PropertyTags()
        {
            _serializer = GetSerializer();
        }

        protected override string SerializeValue(IEnumerable<string> value)
        {
            var result = new StringBuilder();
            _serializer.Serialize(new StringWriter(result), value);
            return result.ToString();
        }

        protected override IEnumerable<string> DeserializeValue(string serializedValue)
        {
            try
            {
                return _serializer.Deserialize<IEnumerable<string>>(new StringReader(serializedValue))
                                  .Where(id => id != "")
                                  .Select(id => id);
            }
            catch (Exception e)
            {
                return serializedValue.Split(',').Where(id => id != "");
            }
        }

        protected override IEnumerable<string> DefaultValue
        {
            get { return Enumerable.Empty<string>(); }
        }

        protected override LongStringProperty<IEnumerable<string>> CreateInstance(IEnumerable<string> value)
        {
            return new PropertyTags { Value = value };
        }
    }
}